#include <iostream>
#include "Master.h"

using namespace std;

void *Master::manageObs(void *arg)
{
	void **param = (void**)(arg);
	Master *m = (Master*)(param[0]);
	obs *o = (obs*)(param[1]);
	
	int status = 0;
	string msg = "";
	long size = 0;
	
	cout << "Un nouvel observateur est en ligne : " << o->login << endl;
	char p = m->proto["OBS/LISTE"];
	o->sock.sendMsg((void*)(&p), 1);
	size = m->rooms.size();
	o->sock.send4(size);
	roomIter it, itEnd = m->rooms.end();
	for(it = m->rooms.begin(); it != itEnd; ++it)
	{
		o->sock.send4(it->name.size());
		o->sock.sendMsg(it->name.c_str(), it->name.size());
	}
	
	status = m->getProto(msg, &o->sock);
	if(status > 0 && msg == "OBS/CHOIX")
	{
		o->sock.read4(&size);
		status = m->getString(o->roomname, size, &o->sock);
		if(status > 0 && !m->checkRoom(o->roomname))
		{
			m->sendProto("OBS/OK/CHOIX", &o->sock);
			status = m->getProto(msg, &o->sock);
			if(status > 0 && msg == "OBS/ACTIVITES")
			{
				room r;
				r.name = o->roomname;
				cout << "Nouvelle salle : " << o->roomname << endl;
				status = o->sock.read4(&size);
				long str_size = 0;
				for(int i=0; i<size; i++)
				{
					string act = "";
					status = o->sock.read4(&str_size);
					if(status <= 0)
						break;
					status = m->getString(act, str_size, &o->sock);
					if(status <= 0)
						break;
					r.activities.push_back(act);
					cout << "     Nouvelle activité : " << act << endl;
				}
				m->rooms.push_back(r);
				
				m->sendProto("OBS/ACTIVITES/OK", &o->sock);
				o->sock.send4(size);
				vector<string>::iterator it, itEnd;
				for(it = r.activities.begin(); it != r.activities.end(); ++it)
				{
					o->sock.send4((*it).size());
					o->sock.sendMsg((*it).c_str(), (*it).size());
				}
				
				////// CORRECTION D4UN BUG A LARRACHE .... DESOLE, ... IL EST MINUIT 30
				// on récup le vrai Obs (le notre est une pale copie du vrai, ahaha ...) mais il faudrait tou changer sinon ...
				for(vector<obs>::iterator it = m->obss.begin(); it != m->obss.end(); ++it)
				{
					if(it->login == o->login)
						it->roomname = o->roomname;
				}
				
			}
			else
				m->sendProto("OBS/ERR/CHOIX", &o->sock);
		}
		else
			m->sendProto("OBS/OK/CHOIX", &o->sock);

		while(1)
		{
			// reste connecté ...
			sleep(10);
		}
	}
	else
		m->sendProto("OBS/ERR/CHOIX", &o->sock);
}
